package com.net.xpay.core.validator;

import com.google.common.base.Strings;
import com.net.xpay.common.domain.User;
import com.net.common.exception.BusinessException;
import com.net.common.util.SerializationUtil;
import com.net.xpay.core.constant.PoseidonErrorCode;
import com.net.xpay.core.model.BookAccountTransferOrderModel;
import com.net.xpay.core.utils.MoneyCheckUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;

@Slf4j
@Component
public class BookAccountTransferOrderValidator {

    public void validateBookTransfer(User user, BookAccountTransferOrderModel model) {
        log.info("validateBookTransfer userId={}|model={}", user.getId(), SerializationUtil.obj2String(model));
        if (Strings.isNullOrEmpty(model.getImportBizNo())) {
            throw new BusinessException(PoseidonErrorCode.PARAMETER_ILLEGAL, "外部订单号不能为空");
        }
        if (model.getImportBizNo().length() > 64) {
            throw new BusinessException(PoseidonErrorCode.PARAMETER_ILLEGAL, "外部订单号长度不能超过64个字符");
        }
        if (Strings.isNullOrEmpty(model.getPayerAlipayAccount())) {
            throw new BusinessException(PoseidonErrorCode.PARAMETER_ILLEGAL, "付款方支付宝账号不能为空");
        }
        if (Strings.isNullOrEmpty(model.getPayeeAlipayAccount())) {
            throw new BusinessException(PoseidonErrorCode.PARAMETER_ILLEGAL, "收款方支付宝账号不能为空");
        }
        if (Strings.isNullOrEmpty(model.getTransAmount())) {
            throw new BusinessException(PoseidonErrorCode.PARAMETER_ILLEGAL, "转账金额不能为空");
        }
        if (!MoneyCheckUtil.isValidMoney(model.getTransAmount(), 2)) {
            throw new BusinessException(PoseidonErrorCode.PARAMETER_ILLEGAL, "转账金额格式错误，最多2位小数");
        }
        if (Strings.isNullOrEmpty(model.getOrderTitle())) {
            throw new BusinessException(PoseidonErrorCode.PARAMETER_ILLEGAL, "转账业务的标题不能为空");
        }
        if (model.getOrderTitle().length() > 32) {
            throw new BusinessException(PoseidonErrorCode.PARAMETER_ILLEGAL, "转账业务的标题不能超过32个字符");
        }
        if (new BigDecimal(model.getTransAmount()).compareTo(new BigDecimal("50000")) >= 0) {
            if (Strings.isNullOrEmpty(model.getRemark())) {
                throw new BusinessException(PoseidonErrorCode.PARAMETER_ILLEGAL, "转账金额超过5万，转账备注不能为空");
            }
        }
        if (new BigDecimal(model.getTransAmount()).compareTo(new BigDecimal("0.1")) < 0) {
            throw new BusinessException(PoseidonErrorCode.PARAMETER_ILLEGAL, "转账金额不能低于0.1元");
        }
        if (!Strings.isNullOrEmpty(model.getRemark()) && model.getRemark().length() > 32) {
            throw new BusinessException(PoseidonErrorCode.PARAMETER_ILLEGAL, "转账备注不能超过32个字符");
        }
    }
}
